import { router } from '@/router'
import { MenuItemType } from 'antd/es/menu/interface'
import React from 'react'
import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'

// 递归生成菜单项
const getMenuItems = (routes?: typeof router.routes): AppMenuItem[] => {
  return routes?.length
    ? routes?.map((route) => ({
        key: route.index ? '/' : (route.path ?? ''),
        name: route.handle?.name || '',
        label: route.handle?.title || route.path,
        showFolderSider: route.handle?.showFolderSider || false,
        children: route.children ? getMenuItems(route.children) : null,
        icon: route.handle?.icon ? React.createElement(route.handle.icon) : null
      }))
    : []
}

// immer 中间件让我们可以在不直接修改状态的情况下编写更简洁的更新逻辑
export const useIndexStore = create<IndexState>()(
  immer((set) => ({
    currentTitle: '笔记',
    selectedKey: '/',
    menus: [],

    setTitle: (title: string) => {
      set({ currentTitle: title })
    },
    setSelectedKey: (key: string) => {
      set({ selectedKey: key })
    },
    setMenus: () => {
      set({ menus: getMenuItems(router.routes[0].children) })
    }
  }))
)

interface AppMenuItem extends MenuItemType {
  showFolderSider: boolean
  name: string
}
interface IndexState {
  currentTitle: string
  selectedKey: string
  menus: AppMenuItem[]
  setTitle: (title: string) => void
  setSelectedKey: (key: string) => void
  setMenus: () => void
}
